package com.tuling.api.utils;





import com.tuling.api.filter.BodyReaderHttpServletRequestWrapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 公共方法
 * 
 *
 */

public class CommonUtil {

	private static final Logger logger= LogManager.getLogger(CommonUtil.class);
	
	/**
	 * 获取http请求头部信息
	 * @author ljp
	 * @param request
	 * @return
	 */

	public static Map<String, String> getHeadersInfo(HttpServletRequest request) {
	    Map<String, String> map = new HashMap<String, String>();
	    Enumeration headerNames = request.getHeaderNames();
	    while (headerNames.hasMoreElements()) {
	        String key = (String) headerNames.nextElement();
	        String value = request.getHeader(key);
	        map.put(key, value);
	    }
	    return map;
	  }

	/**
     * 获取请求参数
     * @param request
     * @return
     */

    public static String getParamString(HttpServletRequest request) {

		StringBuilder param = new StringBuilder();
		BufferedReader bufferedReader = null;
		try{
			bufferedReader = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream(), "UTF-8"));
			String line = bufferedReader.readLine();
			while(null!=line){
				param.append(line);
				line = bufferedReader.readLine();
			}
		}catch(Exception e){
			logger.info("【解析JSON参数】异常，msg:{}"+e.getMessage());
		}finally {
			if(bufferedReader!=null){
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return param.toString();
	}

	public static String getParams(HttpServletRequest request){
		String requestParam=null;
		try {
			requestParam=new BodyReaderHttpServletRequestWrapper(request).getBody();
		} catch (IOException e) {
			return null;
		}
		return requestParam;
	}

}
